package com.mgq.algorithm.graph;

/**
 * @author MaGuangQi
 * 将二维矩阵数组转换为图
 * [5,0,1]
 * [1,2,2]
 * [3,4,3]
 *
 * 假设[0]为from,[1]为to [2]为权重
 *[from,to,weight]
 * @date 2022-01-03 21:51
 **/
public class ChangeGraph {

    /**
     * 将矩阵数据转换为图结构
     * @param matrix
     * @return
     */
    public Graph createGraph(Integer[][] matrix) {
        Graph graph = new Graph();
        for (int i = 0; i < matrix.length; i++) {
            Integer from = matrix[i][0];
            Integer to = matrix[i][1];
            Integer weight = matrix[i][2];
            //不包含from节点,加入到nodes map中
            if (!graph.nodes.containsKey(from)) {
                graph.nodes.put(from, new Node(from));
            }
            if (!graph.nodes.containsKey(to)) {
                graph.nodes.put(to, new Node(to));
            }
            //创建边
            Node fromNode = graph.nodes.get(from);
            Node toNode = graph.nodes.get(to);
            Edge edge = new Edge(weight, fromNode, toNode);
            //将toNode加入到 fromNode的领边结合
            fromNode.nexts.add(toNode);
            //出度加+1 from指向to from->to
            fromNode.out++;
            //toNode的入度+1
            toNode.in++;
            fromNode.edges.add(edge);
            graph.edges.add(edge);
        }
        return graph;
    }
}
